import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel
from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor
from PyQt5.QtCore import Qt, QTimer
from jiemian import Ui_MainWindow
from PyQt5.Qt import *

class CarWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.car_width = 20
        self.car_length = 25
        self.car_position = [45, 270]  # 初始小车位置
        self.car_angle = 0  # 初始小车角度

        self.map_image = QPixmap("map.png")  # 地图图片
        self.setWindowTitle("智能小车模拟")
        self.setFixedSize(self.map_image.width(), self.map_image.height())

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_car_position)
        self.timer.start(100)


    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(0, 0, self.map_image)

        # 绘制小车
        painter.setPen(QPen(QColor(Qt.red), 2, Qt.SolidLine))
        painter.translate(self.car_position[0], self.car_position[1])
        painter.rotate(self.car_angle)
        painter.drawRect(-self.car_width/2, -self.car_length/2, self.car_width, self.car_length)

    def update_car_position(self):
        # 在这里实现小车的自动巡线逻辑
        # 获取传感器数据、计算小车位置和角度等

        # 更新小车位置和角度
        self.car_position[1] += -5  # 假设每次向前移动5个单位
        self.car_angle += 0  # 假设每次逆时针旋转10度

        # 截取小车当前位置的放大图片

        # 刷新界面
        self.update()



class ScreenshotWidget(QWidget):
    def __init__(self, target_widget):
        super().__init__()
        self.screenshot_label = QLabel(self)
        self.screenshot_label.setFixedSize(400,300)  # 设置截图显示区域的大小

        self.target_widget = target_widget
        self.car_width = self.target_widget.car_width
        self.car_length = self.target_widget.car_length
        self.car_position = self.target_widget.car_position
        self.car_angle = self.target_widget.car_angle

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_screenshot)
        self.timer.start(100)  # 每100毫秒更新一次截图

    def update_screenshot(self):
        screenshot = self.target_widget.grab()  # 截取目标控件的屏幕截图
        screenshot_rect = QRect(self.car_position[0]-20, self.car_position[1]-20 , 50, 50)
        screenshot = screenshot.copy(screenshot_rect)  # 截取小车当前位置的放大图片
        self.screenshot_label.setPixmap(screenshot.scaled(self.screenshot_label.size(), Qt.AspectRatioMode.KeepAspectRatio))



class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        car_widget = CarWidget()  # 创建小车模拟界面对象
        self.verticalLayout.addWidget(car_widget)  # 将小车模拟界面添加到布局管理器中
        screenshot_widget = ScreenshotWidget(car_widget)
        self.verticalLayout_2.addWidget(screenshot_widget)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

